package me.yangteng.zhihudaily.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.yangteng.zhihudaily.R;
import me.yangteng.zhihudaily.component.SwipeBackActivity;
import me.yangteng.zhihudaily.model.Story;
import me.yangteng.zhihudaily.util.HttpLoader;
import me.yangteng.zhihudaily.util.LocalStoryLoader;
import me.yangteng.zhihudaily.util.Url;

public class StoryDetailActivity extends SwipeBackActivity {

  private static final String TAG = "StoryDetail";
  private Bundle bundle;
  private String mStoryId;
  private Story story;
  private Gson gson;
  private LocalStoryLoader localStoryLoader;

  private ImageView storyBanner;
  private WebView storyWebView;
  private TextView storyTitle, bannerImageCopyright;
  private View view;

  private SwipeBackLayout swipeBackLayout;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_story_detail, null);
//    setContentView(R.layout.activity_story_detail);
    setContentView(view);

    swipeBackLayout = getSwipeBackLayout();
    swipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);

    gson = new Gson();
    localStoryLoader = new LocalStoryLoader(getApplicationContext());

    bundle = getIntent().getExtras();
    if (bundle != null && bundle.containsKey("storyId")) {
      mStoryId = bundle.getString("storyId");
    } else {
      this.finish();
    }
    storyBanner = (ImageView) this.findViewById(R.id.storyDetailBannerImage);
    storyWebView = (WebView) this.findViewById(R.id.storyDetailWebView);
    storyTitle = (TextView) this.findViewById(R.id.storyDetailTitle);
    bannerImageCopyright = (TextView) this.findViewById(R.id.storyDetailBannerImageCopyright);

    storyWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);

    fetchStory();
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    bundle = intent.getExtras();
    if (bundle != null && bundle.containsKey("storyId")) {
      mStoryId = bundle.getString("storyId");
    } else {
      this.finish();
    }
    fetchStory();
  }

  private void fetchStory() {
    if (localStoryLoader.has(Story.STORAGE_PREFIX + mStoryId)) {
      story = gson.fromJson(localStoryLoader.load(Story.STORAGE_PREFIX + mStoryId), Story.class);
      renderStory();
    } else {
      HttpLoader httpLoader = new HttpLoader();
      httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
        @Override
        public void onGetHttpString(String string) {
          story = gson.fromJson(string, Story.class);
          story.setStorageKey(Story.STORAGE_PREFIX + mStoryId);
          localStoryLoader.save(story);
          renderStory();
        }

        @Override
        public void onError(Exception e) {
          HttpLoader.onErrorHandler(view);
        }
      });
      httpLoader.execute(Url.STORY_CONTENT + this.mStoryId);
    }
  }

  private void renderStory() {
    storyTitle.setText(story.getTitle());
    bannerImageCopyright.setText(story.getImage_source());

    storyWebView.setWebViewClient(new WebViewClient());
    storyWebView.loadData(getHtmlData(), "text/html; charset=utf-8", "utf-8");
    storyWebView.getSettings().setJavaScriptEnabled(true);

    Picasso.with(this.getApplicationContext())
      .load(story.getImage())
      .into(storyBanner);
  }


  private String getHtmlData() {
    StringBuilder head = new StringBuilder();
    head.append("<head>" +
      "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
      "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
    );
    for (String css : story.getCss()) {
      head.append("<link href=\"" + css + "\" rel=\"stylesheet\">");
    }
    head.append("</head>");
    return "<!DOCTYPE html><html>" + head.toString() + "<body>" + story.getBody() + "</body></html>";
  }

  private class WebViewClient extends android.webkit.WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      Uri uri = Uri.parse(url);
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
      return true;
    }
  }
}
